"use client"

import { useState, useEffect } from "react"
import { View, Text, StyleSheet, Modal, TouchableOpacity, Platform, TextInput, Image } from "react-native"
import { LinearGradient } from "expo-linear-gradient"
import { Calendar, X } from "lucide-react-native"
import { theme } from "@/constants/theme"
import Slider from "@react-native-community/slider"

interface CreatePlanModalProps {
    visible: boolean
    onClose: () => void
    onSubmit: (PlanData) => void
    onDelete?: () => void
    currentBook: {
        id: string
        title: string
        total: number
    }
    hasExistingPlan?: boolean
}

interface PlanData {
    name: string
    wordsPerDay: number
    totalDays: number
    startDate: string
    endDate: string
}

export function CreatePlanModal(props: CreatePlanModalProps) {
    const { visible, onClose, onSubmit, currentBook } = props
    const [planName, setPlanName] = useState(`${currentBook.title}学习计划`)
    const [wordsPerDay, setWordsPerDay] = useState(3)
    const [totalDays, setTotalDays] = useState(0)
    const [startDate, setStartDate] = useState(new Date().toISOString().split("T")[0])
    const [endDate, setEndDate] = useState("")

    // Calculate total days when words per day changes
    useEffect(() => {
        if (currentBook?.total && wordsPerDay > 0) {
            const days = Math.ceil(currentBook.total / wordsPerDay)
            setTotalDays(days)

            // Update end date
            const endDate = new Date()
            endDate.setDate(endDate.getDate() + days)
            setEndDate(endDate.toISOString().split("T")[0])
        }
    }, [wordsPerDay, currentBook?.total])

    // Update words per day when total days changes
    const handleDaysChange = (days: number) => {
        if (currentBook?.total && days > 0) {
            setTotalDays(days)
            const words = Math.ceil(currentBook.total / days)
            setWordsPerDay(words)

            // Update end date
            const endDate = new Date()
            endDate.setDate(endDate.getDate() + days)
            setEndDate(endDate.toISOString().split("T")[0])
        }
    }

    const handleSubmit = () => {
        onSubmit({
            name: planName || `${currentBook.title}学习计划`,
            wordsPerDay,
            totalDays,
            startDate,
            endDate,
        })
    }

    if (!visible) return null

    return (
        <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
            <View style={styles.overlay}>
                <View style={styles.container}>
                    {/* Header */}
                    <View style={styles.header}>
                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png" }}
                            style={styles.headerIcon}
                        />
                        <Text style={styles.headerTitle}>制定学习计划</Text>
                        <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                            <X size={20} color={theme.colors.neutral.gray} />
                        </TouchableOpacity>
                    </View>

                    {/* Content */}
                    <View style={styles.content}>
                        {/* Plan Name */}
                        <View style={styles.inputGroup}>
                            <Text style={styles.label}>计划名称</Text>
                            <TextInput
                                style={styles.input}
                                placeholder={`${currentBook.title}学习计划`}
                                value={planName}
                                onChangeText={setPlanName}
                                placeholderTextColor={theme.colors.neutral.gray}
                            />
                        </View>

                        {/* Learning Speed */}
                        <View style={styles.inputGroup}>
                            <Text style={styles.label}>学习进度</Text>
                            <View style={styles.speedCard}>
                                <View style={styles.speedRow}>
                                    <View style={styles.speedItem}>
                                        <Text style={styles.speedValue}>{wordsPerDay}</Text>
                                        <Text style={styles.speedLabel}>每日新词</Text>
                                    </View>
                                    <View style={styles.speedDivider} />
                                    <View style={styles.speedItem}>
                                        <Text style={styles.speedValue}>{totalDays}</Text>
                                        <Text style={styles.speedLabel}>所需天数</Text>
                                    </View>
                                </View>

                                {/* Words Per Day Slider */}
                                <View style={styles.sliderContainer}>
                                    <Text style={styles.sliderLabel}>每日新词数量</Text>
                                    <Slider
                                        style={styles.slider}
                                        minimumValue={1}
                                        maximumValue={10}
                                        step={1}
                                        value={wordsPerDay}
                                        onValueChange={setWordsPerDay}
                                        minimumTrackTintColor={theme.colors.primary.default}
                                        maximumTrackTintColor={theme.colors.neutral.lightGray}
                                        thumbTintColor={theme.colors.primary.default}
                                    />
                                    <View style={styles.sliderValues}>
                                        <Text style={styles.sliderMinValue}>1词/天</Text>
                                        <Text style={styles.sliderMaxValue}>10词/天</Text>
                                    </View>
                                </View>

                                {/* Total Days Slider */}
                                <View style={styles.sliderContainer}>
                                    <Text style={styles.sliderLabel}>计划天数</Text>
                                    <Slider
                                        style={styles.slider}
                                        minimumValue={Math.ceil(currentBook.total / 10)}
                                        maximumValue={Math.ceil(currentBook.total)}
                                        step={1}
                                        value={totalDays}
                                        onValueChange={handleDaysChange}
                                        minimumTrackTintColor={theme.colors.primary.default}
                                        maximumTrackTintColor={theme.colors.neutral.lightGray}
                                        thumbTintColor={theme.colors.primary.default}
                                    />
                                    <View style={styles.sliderValues}>
                                        <Text style={styles.sliderMinValue}>{Math.ceil(currentBook.total / 10)}天</Text>
                                        <Text style={styles.sliderMaxValue}>{Math.ceil(currentBook.total)}天</Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        {/* Date Selection */}
                        <View style={styles.inputGroup}>
                            <Text style={styles.label}>学习时间</Text>
                            <View style={styles.dateContainer}>
                                <TouchableOpacity style={styles.dateButton}>
                                    <Text style={styles.dateButtonText}>{startDate}</Text>
                                    <Calendar size={16} color={theme.colors.primary.default} />
                                </TouchableOpacity>
                                <Text style={styles.dateSeparator}>至</Text>
                                <TouchableOpacity style={styles.dateButton}>
                                    <Text style={styles.dateButtonText}>{endDate}</Text>
                                    <Calendar size={16} color={theme.colors.primary.default} />
                                </TouchableOpacity>
                            </View>
                        </View>

                        {/* Word Count Info */}
                        <View style={styles.wordCountInfo}>
                            <Text style={styles.wordCountText}>单词总数：{currentBook.total}</Text>
                            <Text style={styles.wordCountText}>剩余单词数：{currentBook.total}</Text>
                        </View>
                    </View>

                    {/* Footer */}
                    <View style={styles.footer}>
                        {props.hasExistingPlan && props.onDelete && (
                            <TouchableOpacity style={styles.deleteButton} onPress={props.onDelete}>
                                <Text style={styles.deleteButtonText}>清除计划</Text>
                            </TouchableOpacity>
                        )}
                        <TouchableOpacity style={styles.cancelButton} onPress={onClose}>
                            <Text style={styles.cancelButtonText}>取消</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
                            <LinearGradient
                                colors={theme.colors.primary.gradient}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                                style={styles.submitButtonGradient}
                            >
                                <Text style={styles.submitButtonText}>{props.hasExistingPlan ? "更新计划" : "开启科学背单词之旅"}</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        backgroundColor: "rgba(0, 0, 0, 0.5)",
        justifyContent: "center",
        alignItems: "center",
    },
    container: {
        width: "90%",
        maxWidth: 400,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.medium,
                shadowOffset: { width: 0, height: 8 },
                shadowOpacity: 0.3,
                shadowRadius: 12,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        padding: theme.spacing.lg,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.neutral.lightGray,
        position: "relative",
    },
    headerIcon: {
        width: 24,
        height: 24,
        marginRight: theme.spacing.sm,
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    closeButton: {
        position: "absolute",
        right: theme.spacing.lg,
        padding: theme.spacing.sm,
    },
    content: {
        padding: theme.spacing.lg,
    },
    inputGroup: {
        marginBottom: theme.spacing.xl,
    },
    label: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
    },
    input: {
        backgroundColor: theme.colors.neutral.background,
        borderRadius: theme.borderRadius.large,
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: Platform.OS === "ios" ? theme.spacing.lg : theme.spacing.md,
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
        borderWidth: 1,
        borderColor: theme.colors.neutral.lightGray,
    },
    speedCard: {
        backgroundColor: theme.colors.neutral.background,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
    },
    speedRow: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-around",
        marginBottom: theme.spacing.lg,
    },
    speedItem: {
        alignItems: "center",
    },
    speedValue: {
        fontSize: theme.fontSize.xxl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.xs,
    },
    speedLabel: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    speedDivider: {
        width: 1,
        height: 40,
        backgroundColor: theme.colors.neutral.lightGray,
    },
    sliderContainer: {
        marginTop: theme.spacing.lg,
    },
    sliderLabel: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
        marginBottom: theme.spacing.sm,
    },
    slider: {
        width: "100%",
        height: 40,
    },
    sliderValues: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: theme.spacing.xs,
    },
    sliderMinValue: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.gray,
    },
    sliderMaxValue: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.gray,
    },
    dateContainer: {
        flexDirection: "row",
        alignItems: "center",
    },
    dateButton: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        backgroundColor: theme.colors.neutral.background,
        borderRadius: theme.borderRadius.large,
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.lg,
        borderWidth: 1,
        borderColor: theme.colors.neutral.lightGray,
    },
    dateButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
    },
    dateSeparator: {
        paddingHorizontal: theme.spacing.md,
        color: theme.colors.neutral.darkGray,
    },
    wordCountInfo: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: theme.spacing.md,
    },
    wordCountText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    footer: {
        flexDirection: "row",
        padding: theme.spacing.lg,
        gap: theme.spacing.md,
        borderTopWidth: 1,
        borderTopColor: theme.colors.neutral.lightGray,
    },
    cancelButton: {
        flex: 1,
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
    },
    cancelButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    submitButton: {
        flex: 2,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    submitButtonGradient: {
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    submitButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    deleteButton: {
        flex: 1,
        backgroundColor: "#FEE4E2",
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
    },
    deleteButtonText: {
        fontSize: theme.fontSize.md,
        color: "#D92D20",
        fontWeight: theme.fontWeight.medium,
    },
})

